package history.link.doublycircularlinklist;

import java.util.Iterator;

/**
 * @author czt
 * @version 1.0
 * @since 2024/10/28
 */
public class DoublyCircularLinkListSentinel implements Iterable<Integer>{

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = sentinel.next;
            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    private static class Node {

        Node prev;

        int value;

        Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    private Node sentinel = new Node(null, -1, null);

    public DoublyCircularLinkListSentinel() {
        sentinel.prev = sentinel;
        sentinel.next = sentinel;
    }

    public void addFirst(int value) {
        //要在s和h之间插入节点
        Node s = sentinel; //哨兵节点
        Node h = sentinel.next; //当前头节点

        Node node = new Node(s, value, h);
        sentinel.next = node;
        h.prev = node;
    }

    public void addLast(int value) {
        Node prev = sentinel.prev;
        Node node = new Node(prev, value, sentinel);

        sentinel.prev = node;
        prev.next = node;
    }

    public void removeFirst() {
        Node removed = sentinel.next;//待删除的节点，第一个节点
        if (removed == sentinel) {
            throw new IllegalArgumentException();
        }
        Node a = sentinel; //待删除节点的上一个节点，哨兵节点
        Node b = removed.next;//待删除节点的后一个节点

        a.next = b;
        b.prev = a;
    }

    public void removeLast() {
        Node removed = sentinel.prev; //待删除节点，最后一个节点

        Node prev = removed.prev; //待删除节点的上一个节点

        prev.next = sentinel;
        sentinel.prev = prev;
    }

    //根据节点值查找节点
    private Node findByValue(int value) {
        Node p = sentinel.next;
        while (p != sentinel) {
            if (p.value == value) {
                return p;
            }
            p = p.next;
        }
        return null;
    }

    public void removeByValue(int value) {
        Node removed = findByValue(value);
        if (removed == null) {
            return; //不用删
        }

        Node a = removed.prev;
        Node b = removed.next;
        a.next = b;
        b.prev = a;
    }
}
